package com.ruoyi.framework.interceptor;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ruoyi.common.utils.LicenseUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;

/**
 * 授权许可拦截器
 * 
 * @author ruoyi
 */
@Component
public class LicenseInterceptor extends HandlerInterceptorAdapter
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
    	
    	String flag = StringUtils.convertStr(request.getServletContext().getAttribute("LICENSE_VALIDATION_FLAG"));
    	
    	if ("PASSED".equals(flag)) {
    		return true;
    	}
    	
    	Resource resource = new ClassPathResource("license.lic");
    	
    	if (resource.exists()) {

      	File file = resource.getFile();
      	
      	if (LicenseUtil.licenseVerify(file)) {
      		request.getServletContext().setAttribute("LICENSE_VALIDATION_FLAG", "PASSED");
      		
      		return true;
      	}
    	}
    	
    	String code = LicenseUtil.getMachineCode(null);
    	
      String str = "<div align='center' style='margin-top: 200px;'><div><h1>未授权或授权已过期！</h1></div>";
    	str += "<div><h2>请联系管理员根据机器码生成授权许可证！</h2></div>";
    	str += "<div style='color: red'><h2>机器码："+code+"</h2></div></div>";
    	ServletUtils.renderHtml(response, str);
    	
      return false;
    }

}
